//  this library.
import 'dart:async';

import 'package:flutter/material.dart';
import 'package:hktk_app/ienum/practice/ct_enum.dart';
import 'package:hktk_app/ienum/question/answer_type_enum.dart';
import 'package:hktk_app/ienum/question/question_type_enum.dart';
import 'package:hktk_app/model/question/paper_data_model.dart';
import 'package:hktk_app/model/question/question_data_model.dart';
import 'package:hktk_app/pages/question/child/stem_page.dart';
import 'package:hktk_app/util/data_util.dart';
import 'package:hktk_app/util/event_bus_util.dart';
import 'package:hktk_app/util/my_util.dart';
import 'package:hktk_app/util/sz_util.dart';
import 'package:hktk_app/util/toast_util.dart';
import 'package:hktk_app/util/view_util.dart';
import 'package:hktk_app/widget/question/stem_analysis_widget.dart';
import 'package:hktk_app/widget/question/stem_answer_widget.dart';
import 'package:hktk_app/widget/question/stem_note_widget.dart';
import 'package:hktk_app/widget/question/stem_option_widget.dart';
import 'package:hktk_app/widget/question/stem_rich_text_widget.dart';
import 'package:hktk_app/widget/question/stem_text_widget.dart';
import 'package:hktk_app/widget/question/stem_title_widget.dart';

/// 试题、题干等相关页面
class StemExamPage extends StatefulWidget {
  /// 试题模式，ture-答题，false-背题
  final QuestionTypeEnum type;

  /// 试题加载数据方法
  final QuestionInit quesInit;

  /// 对应试题下标
  final int index;

  const StemExamPage({
    super.key,
    required this.index,
    required this.type,
    required this.quesInit,
  });

  @override
  State<StemExamPage> createState() => _StemExamPageState();
}

class _StemExamPageState extends State<StemExamPage>
    with AutomaticKeepAliveClientMixin {
  late BuildContext _context;

  /// 是否是第一次加载
  late bool _init;

  /// 答案是否发生改变
  late bool _ansChange;

  /// 考试模式，0：默认，1：退出获取数据，2：交卷获取数据
  late int _examData;

  /// 试题相关信息
  late DtkInfoModel _dtk;

  /// 试题信息
  late QuestionDataModel _dataModel;

  /// 选中的值
  late List<String> _selectedList;

  /// 加载数据初始化方法
  late Future<Map<String, dynamic>> _futureInit;

  /// 监听对应广播
  late StreamSubscription<EventQuestionOnZTDX> _eventOnZTDX;

  late StreamSubscription<EventQuestionOnPage> _eventOnPage;

  late StreamSubscription<EventQuestionExamJj> _eventExamJj;

  @override
  void initState() {
    super.initState();

    _init = true;
    _selectedList = [];
    _ansChange = false;
    _examData = 0;
    _futureInit = widget.quesInit(
      dataUtilComm.paperData!.dtkList[widget.index].id,
      dataUtilComm.paperData!.collectId,
    );

    // 监听方法
    _eventOnZTDX = eventBus.on<EventQuestionOnZTDX>().listen((event) {
    setState(() {});
    });

    _eventOnPage = eventBus.on<EventQuestionOnPage>().listen((event) {
       if (widget.type == event.type) {
        int ii = widget.index - event.index;
        // 取绝对值，判断只移动了一个页面
        if (ii.abs() == 1 || event.dtkTz) {
          if (MyUtil.getDXXZT(_dtk.type) || MyUtil.getBDXXZT(_dtk.type)) {
            _answerJudgment();
          } else if (MyUtil.getTKT(_dtk.type) || MyUtil.getWDT(_dtk.type)) {
            eventBus.fire(EventQuestionOnOpt(qId: _dtk.id));
          }
        }
      }
    });

    _eventExamJj = eventBus.on<EventQuestionExamJj>().listen((event) {
      debugPrint(
          "stemExamPage 页面 -> ${widget.index} 页面 获取答案监听 ===> ${_dtk.id} : ${event.id}，模式：${event.exam == 1 ? "退出" : "交卷"}");
      if (event.id == _dtk.id) {
        _examData = event.exam;
        if (MyUtil.getDXXZT(_dtk.type) || MyUtil.getBDXXZT(_dtk.type)) {
          _answerJudgment();
        } else if (MyUtil.getTKT(_dtk.type) || MyUtil.getWDT(_dtk.type)) {
          eventBus.fire(EventQuestionOnOpt(qId: _dtk.id));
        }
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
    debugPrint("stemExamPage 页面 -> dispose 方法执行 ===> ${widget.index}");
    debugPrint("");
    _eventOnZTDX.cancel();
    _eventOnPage.cancel();
    _eventExamJj.cancel();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    debugPrint("stemExamPage 页面 -> build 方法执行 ===> ${widget.index}");
    debugPrint("");
    _context = context;
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 30),
      decoration: BoxDecoration(
        color: getColorWhite1b12(szYjms: szUtilComm.szInfo.yjms),
      ),
      child: _futureData(),
    );
  }

  /// 加载数据方法
  _futureData() {
    return FutureBuilder<Map<String, dynamic>>(
      future: _futureInit,
      builder: (
          BuildContext context,
          AsyncSnapshot<Map<String, dynamic>> snapshot,
          ) {
        if (snapshot.connectionState == ConnectionState.done) {
          if (_init) {
            Map<String, dynamic> map = snapshot.data!;
            if (!map["suc"]) {
              // 加载失败
              if (map["msg"] != "") {
                WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
                  ToastUtil.show(context: _context, msg: map["msg"]);
                });
              }
              return Container(
                color: getColorWhite1b12(szYjms: szUtilComm.szInfo.yjms),
              );
            }
            _dataModel = map["data"];
            _loadData();
            _init = false;
          }
          return _content();
        } else {
          // 加载中
          return const Center(
            child: CircularProgressIndicator(),
          );
        }
      },
    );
  }

  /// 加载数据方法
  _loadData() {
    debugPrint("stemExamPage 页面 -> 存储相关数据方法执行 ===> ");
    dataUtilComm.paperData!.dtkList[widget.index].sign = _dataModel.sign;
    dataUtilComm.paperData!.dtkList[widget.index].st = _dataModel.stem;
    dataUtilComm.paperData!.dtkList[widget.index].answerBase64 =
        _dataModel.answerBase64;
    if (_dataModel.record != null) {
      _selectedList = MyUtil.getUserAnsList(
        _dataModel.record!.as,
        _dataModel.type,
      );
      AnswerTypeEnum ans = _dataModel.record!.rt!
          ? AnswerTypeEnum.success
          : AnswerTypeEnum.error;
      dataUtilComm.paperData!.dtkList[widget.index].userAns = _selectedList;
      dataUtilComm.paperData!.dtkList[widget.index].ansType = ans;
    } else {
      _selectedList = dataUtilComm.paperData!.dtkList[widget.index].userAns;
    }
  }

  /// 内容显示
  Widget _content() {
    _dtk = dataUtilComm.paperData!.dtkList[widget.index];
    bool showOpt = _getShowOpt();
    bool showDa = _getShowDa();
    bool showBj = _getShowBj(showDa);
    return MediaQuery.removePadding(
      removeTop: true,
      context: _context,
      child: ListView(
        children: [
          hiSpace(height: 24),
          _titleItem(),
          hiSpace(height: 26),
          _stemItem(),
          hiSpace(height: 40),
          if (showOpt) _optionItem(),
          if (!showOpt) _textItem(),
          if (showDa) hiSpace(height: 75),
          if (showDa) _answerItem(),
          if (showDa) hiSpace(height: 60),
          if (showDa) _analysisItem(),
          if (showBj) hiSpace(height: 60),
          if (showBj) _nodeItem(),
          hiSpace(height: 28),
        ],
      ),
    );
  }

  /// 是否显示选项
  bool _getShowOpt() {
    bool show = true;
    if (MyUtil.getTKT(_dtk.type) || MyUtil.getWDT(_dtk.type)) {
      show = false;
    }
    return show;
  }

  /// 是否显示答案
  bool _getShowDa() {
    return widget.type == QuestionTypeEnum.examEnd ||
        widget.type == QuestionTypeEnum.dailyRecord ||
        widget.type == QuestionTypeEnum.check;
  }

  /// 是否显示笔记方法
  bool _getShowBj(bool showDa) {
    bool show = showDa;
    if (dataUtilComm.paperData!.rType == CtEnum.everyday) {
      show = false;
    }
    return show;
  }

  /// 添加内边距
  _showPadding(Widget childV) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 10),
      child: childV,
    );
  }

  /// 题型收藏显示
  _titleItem() {
    return _showPadding(
      StemTitleWidget(
        index: widget.index,
        type: widget.type,
      ),
    );
  }

  /// 题干显示
  _stemItem() {
    String tg = _dataModel.getStemStr();
    return _showPadding(
      StemRichTextWidget(
        text: tg,
      ),
    );
  }

  /// 选项显示
  _optionItem() {
    return _showPadding(
      StemOptionWidget(
        optionList: _dataModel.optionList,
        showDa: _getShowDa(),
        selectedChanged: _onTapFunXx,
        selectedList: _selectedList,
        type: widget.type,
        answer: _dataModel.answer,
        qType: _dtk.type,
      ),
    );
  }

  /// 选项反应方法-选项被点击选择时
  _onTapFunXx(String optionV) {
    debugPrint("stemExamPage 页面 -> 选中返回值为 ===> $optionV");
    // 判断题型
    if (MyUtil.getDXT(_dtk.type) || MyUtil.getPDT(_dtk.type)) {
      _selectedList = [optionV];
      _ansChange = true;
      _answerJudgment();
    } else if (MyUtil.getDXXZT(_dtk.type) || MyUtil.getBDXXZT(_dtk.type)) {
      // 判断是否选中
      bool sel = _selectedList.contains(optionV);
      if (sel) {
        // 选中
        _selectedList.remove(optionV);
      } else {
        // 未选中
        _selectedList.add(optionV);
      }
      _ansChange = true;
      setState(() {});
    }
  }

  /// 输入框显示方法
  _textItem() {
    return _showPadding(
      StemTextWidget(
        answer: _dataModel.answer,
        qType: _dtk.type,
        showDa: _dtk.ansType != AnswerTypeEnum.notDone,
        qId: _dtk.id,
        onTapFunQd: _textJudgment,
        type: widget.type,
        opList: _dataModel.optionList,
        ansChange: _ansChange,
      ),
    );
  }

  /// 填空问答题判断
  _textJudgment(bool change, List<String> list) {
    // 获取填入数据
    _ansChange = change;
    _selectedList = list;
    _answerJudgment();
  }

  /// 答案判断是否正确，
  _answerJudgment() {
    debugPrint("stemExamPage 页面 -> ${widget.index} 存储答案方法 ===> $_ansChange");
    if (_ansChange) {
      dataUtilComm.paperData!.dtkList[widget.index].userAns = _selectedList;
      dataUtilComm.paperData!.dtkList[widget.index].ansType =
          AnswerTypeEnum.success;
      dataUtilComm.paperData!.dtkList[widget.index].ansDate =
          DateTime.now().millisecondsSinceEpoch;
      dataUtilComm.paperData!.dc++;
      // 保存答案后，未改变
      _ansChange = false;
      // 单选题自动跳转下一题
      if (MyUtil.getDXT(_dtk.type) || MyUtil.getPDT(_dtk.type)) {
        setState(() {});
        eventBus.fire(EventQuestionOnDtk(index: widget.index + 1));
      }
    }
    // 发送请求判断完成
    if (_examData != 0) {
      eventBus.fire(EventQuestionExamData(exam: _examData));
      _examData = 0;
    }
  }

  /// 答案组件
  _answerItem() {
    // 判断是否显示你选择的
    bool showSel = false;
    if (widget.type == QuestionTypeEnum.answer ||
        widget.type == QuestionTypeEnum.examEnd) {
      showSel = _selectedList.isNotEmpty;
    }
    return StemAnswerWidget(
      ans: _dataModel.answer,
      sel: _selectedList,
      suc: _dtk.ansType == AnswerTypeEnum.success,
      showSel: showSel,
      qType: _dtk.type,
      doingNumber: _dataModel.doingNumber,
      errorNumber: _dataModel.errorNumber,
    );
  }

  /// 显示解析组件
  _analysisItem() {
    String text = _dataModel.analysis;
    if (text.isEmpty) {
      text = "暂无";
    }
    return StemAnalysisWidget(
      ana: text,
    );
  }

  /// 笔记组件显示
  _nodeItem() {
    PaperDataModel paperData = dataUtilComm.paperData!;
    return StemNoteWidget(
      qId: _dataModel.id,
      relationId: paperData.collectId,
      relationName: paperData.name,
      stem: _dtk.st!,
      type: MyUtil.getCollTypeEnum(paperData.rType),
    );
  }

  @override
  bool get wantKeepAlive => true;
}
